﻿Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports System.Text.RegularExpressions

Public Class ZuneHelpers

    Public Shared regex_UUID As Regex = New Regex("[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}")

    Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer

    Public Shared Function CreateUUID() As String
        Dim myId As Guid
        Dim code As Integer

        If Not My.Settings.UUIDSequential Then
            myId = System.Guid.NewGuid()
            code = 0
        Else
            code = UuidCreateSequential(myId)
        End If

        If code <> 0 Then
            MsgBox(Format("UuidCreateSequential failed: {0}", code), MsgBoxStyle.Critical, "Create UUID")
            Return ""
        Else
            Return myId.ToString
        End If
    End Function

    Public Shared Function GetArtistZuneUUID(ByVal name As String) As String
        Dim encodedURL, sReturn, uuid As String
        Dim client As New WebClient

        uuid = ""
        encodedURL = "http://social.zune.net/search.aspx?keyword=" + Web.HttpUtility.UrlEncode(name)
        sReturn = client.DownloadString(encodedURL)

        For i As Integer = sReturn.IndexOf("#artist#" + name.Split(" ")(0)) - 1 To 0 Step -1
            If sReturn.Chars(i).ToString = """" Then Exit For
            uuid = sReturn.Chars(i).ToString + uuid
        Next

        Return uuid
    End Function

    Public Shared Sub RelocateZuneDLLs()
        For Each dll As String In IO.Directory.GetFiles(My.Settings.softwareDir)
            If dll.Contains(".dll") Then
                IO.File.Copy(dll, Application.StartupPath + "\" + IO.Path.GetFileName(dll), True)
            End If
        Next
    End Sub

    Public Shared Function nl2br(ByVal source As String) As String
        Return Replace(source, vbNewLine, "#br#")
    End Function

    Public Shared Function br2nl(ByVal source As String, Optional ByVal doubled As Boolean = False) As String
        If doubled Then Return Replace(source, "#br##br#", vbNewLine)
        Return Replace(source, "#br#", vbNewLine)
    End Function

    Public Shared Function IsURIOnline(ByVal uri As String) As IO.Stream
        'Call url
        Dim url As New System.Uri(uri)
        'Request for request
        Dim req As System.Net.HttpWebRequest
        req = System.Net.WebRequest.Create(url)
        Dim resp As System.Net.HttpWebResponse
        Try
            resp = req.GetResponse()
            req = Nothing

            If Not resp.StatusCode = HttpStatusCode.OK Then
                Return Nothing
            Else
                Return resp.GetResponseStream
            End If
        Catch ex As Exception
            req = Nothing
            Return Nothing
        End Try
    End Function

End Class
